package com.itheima.activiti.service;

import com.itheima.activiti.dao.ActGroupMapper;
import com.itheima.activiti.dao.ActRoleMapper;
import com.itheima.activiti.dao.ActUserMapper;
import com.itheima.activiti.domain.ActUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * TODO
 *
 * @author fgy
 * @version 1.0
 * @date 2021/6/21 17:43
 */
@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private ActUserMapper userMapper;
    @Autowired
    private ActGroupMapper groupMapper;
    @Autowired
    private ActRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        ActUser actUser = userMapper.selectByName(username);
        if (actUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Integer id = actUser.getId();
        List<String> gList = groupMapper.selectByUserId(id);
        List<String> rlist = roleMapper.selectByUserId(id);
        if (!CollectionUtils.isEmpty(gList)) {
            if (!CollectionUtils.isEmpty(rlist)) {
                gList.addAll(rlist);
            }
            gList.forEach(p -> {
                authorities.add(new SimpleGrantedAuthority(p));//ROLE_
            });
        } else {
            if (!CollectionUtils.isEmpty(rlist)) {
                rlist.forEach(p -> {
                    authorities.add(new SimpleGrantedAuthority(p));//ROLE_
                });
            }
        }
//        数据库中密码加密这里就不需要加密了，BCryptPasswordEncoder 创建密码时加密即可
        return new User(actUser.getUsername(), new BCryptPasswordEncoder().encode(actUser.getPassword()), authorities);
    }
}
